//
//  StatusPictureView.swift
//  weiboLQ
//
//  Created by 半缘君 on 15/12/12.
//  Copyright © 2015年 banyuanjun.cn. All rights reserved.
//

import UIKit
import SDWebImage
let LQStatusPictureViewCellID = "LQStatusPictureViewCellID"
let StatusPictureViewMargin:CGFloat = 8
class StatusPictureView: UICollectionView {
    /// 微博视图模型
    var viewModel:StatusViewModel?{
        didSet {
            
            sizeToFit()
            
            reloadData()
        }
    }

    override func sizeThatFits(size: CGSize) -> CGSize {
        return getPictureViewSize()
    }
    
    
    //MARK: - 构造方法
    init(){
        let layout = UICollectionViewFlowLayout()
        
        layout.minimumInteritemSpacing = StatusPictureViewMargin
        layout.minimumLineSpacing = StatusPictureViewMargin
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        dataSource = self
        delegate = self
        
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier:LQStatusPictureViewCellID)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


}
// MARK: - 数据源方法
extension StatusPictureView:UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //测试代码LQPhotoBrowserAnimatorDelegate
//        imageViewForPresent(indexPath)
//        photoBrowserPresentFromRect(indexPath)
//        photoBrowserPresentToRect(indexPath)
        
//        print(indexPath)
//        print(viewModel?.thumbnail_pics)
        let infoDict = [LQDidSelectStatusPictureIndexPathKey:indexPath,LQDidSelectStatusPictureURLsKey:viewModel!.thumbnail_pics!]
        NSNotificationCenter.defaultCenter().postNotificationName(LQDidSelectStatusPictureNotification, object: self, userInfo: infoDict)
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
//        StatusViewModel(status: status)
        return viewModel?.thumbnail_pics?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LQStatusPictureViewCellID, forIndexPath: indexPath) as! StatusPictureViewCell
        cell.imageURL = viewModel!.thumbnail_pics![indexPath.item]
        
        return cell
    }
}

private class StatusPictureViewCell:UICollectionViewCell {
    var imageURL:NSURL?{
        didSet {
            iconView.sd_setImageWithURL(imageURL,
                placeholderImage: nil,
                options:[SDWebImageOptions.RetryFailed,
                    SDWebImageOptions.RefreshCached])
//            print(imageURL?.absoluteString);
            let urlString = (imageURL?.absoluteString)! as NSString
            if urlString.hasSuffix(".gif") {
                gifView.hidden = false;
            } else {
                gifView.hidden = true;
            }
            
        }
    }
    lazy var gifView:UIImageView = {
        let iv = UIImageView(imageName: "timeline_image_gif")
        return iv
    }()
    ///懒加载控件
    lazy var iconView:UIImageView = {
       let iv = UIImageView()
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        return iv
    }()
    
    override init(frame:CGRect){
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setupUI () {
        backgroundColor = UIColor.redColor()
        contentView.addSubview(iconView)
        iconView.addSubview(gifView)

        
//        contentView.addSubview()
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        gifView.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(iconView)
            make.right.equalTo(iconView)
        }
    }
}
// MARK: - 转场动画代理
extension StatusPictureView:LQPhotoBrowserAnimatorDelegate {
    func imageViewForPresent(indexPath: NSIndexPath) -> UIImageView {
        let presentImageView = UIImageView()
        
        presentImageView.contentMode = .ScaleAspectFill
        presentImageView.clipsToBounds = true
        
        let key = viewModel!.thumbnail_pics![indexPath.item].absoluteString
        
        presentImageView.image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        
//        测试代码
//        UIApplication.sharedApplication().keyWindow?.
//        addSubview(presentImageView)
        
        presentImageView.sizeToFit()
        
       
        
        return presentImageView
    }
    func photoBrowserPresentFromRect(indexPath: NSIndexPath) -> CGRect {
        guard let cell = self.cellForItemAtIndexPath(indexPath) else {
            return CGRectZero
        }
        
        
        let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        //测试代码
//        let presentImageView = imageViewForPresent(indexPath)
//        presentImageView.frame = rect
//        
//         UIApplication.sharedApplication().keyWindow?.
//        addSubview(presentImageView)
        
        return rect
    }
    func photoBrowserPresentToRect(indexPath: NSIndexPath) -> CGRect {
        let key = viewModel!.thumbnail_pics![indexPath.item].absoluteString
        
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        let size = image.size
        let w = LQScreenBounds.width
        let h = size.height * w / size.width
        var y:CGFloat = 0
        if h < LQScreenBounds.height {
            y = (LQScreenBounds.height - h) / 2
        }
        let rect = CGRectMake(0, y, w, h)
//        let presentImageView = imageViewForPresent(indexPath)
//                presentImageView.frame = rect
//        
//                 UIApplication.sharedApplication().keyWindow?.addSubview(presentImageView)
        return rect
    }
}

// MARK: - 计算pictureView的大小
extension StatusPictureView {
    
    private func getPictureViewSize () -> CGSize {
        //每行的cell个数
        let rowCount = 3
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        
        
        let itemW = (UIScreen.mainScreen().bounds.width - 2.0 * StatusPictureViewMargin - 2.0 * CGFloat(LQHomeCellMargin)) / CGFloat( 3.0)
        layout.itemSize = CGSizeMake(itemW, itemW)
        //获取模型数据
        let picCount = viewModel?.thumbnail_pics?.count ?? 0
        
        switch (picCount){
        case 0:
//            layout.itemSize = CGSize(width: 1, height: 1)
//            print(layout.itemSize)
            return CGSizeZero
        case 1:
            var size = CGSize(width: 150, height: 120)
            
            // 利用 SDWebImage 检查本地的缓存图像 - key 就是 url 的完整字符串
            // 问：SDWebImage 是如何设置缓存图片的文件名 完整 URL 字符串 -> `MD5`
            if let key = viewModel?.thumbnail_pics?.first?.absoluteString {
                
                if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) {
                    
                    size = image.size
                }
            }
            
            // 过窄处理 - 针对长图
            size.width = size.width < 40 ? 40 : size.width
            // 过宽的图片
            if size.width > 300 {
                let w: CGFloat = 300
                let h = size.height * w / size.width
                
                size = CGSize(width: w, height: h)
            }
            
            // 内部图片的大小
            layout.itemSize = size
            
            // 配图视图的大小
            return size
        case 4:
            let w = 2 * itemW + StatusPictureViewMargin
            
            return CGSizeMake(w, w)
//        case 9:
//            let w = 3 * itemW + 2 * StatusPictureViewMargin
//            
//            layout.itemSize = CGSizeMake(w, w)
//            return CGSizeMake(w, w)
        default:
            let numberOfRows = CGFloat((picCount - 1) / rowCount + 1)
            let w = CGFloat(rowCount) * itemW + 2 * StatusPictureViewMargin
            let h = numberOfRows * itemW + (numberOfRows - 1) * StatusPictureViewMargin
            
//            print("\(w) \(h) \(itemW)")
            return CGSizeMake(w, h)


            
        }
    }

}
